package com.ozner.wifi.mxchip;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import com.ozner.device.BaseDeviceIO;
import com.ozner.device.IOManager;
import com.ozner.device.OznerDeviceManager;

import java.util.ArrayList;
import java.util.HashMap;


/**
 * Created by xzyxd on 2015/10/31.
 */
public class MXChipIOManager extends IOManager {
    /**
     * 找到设备广播,附加设备的MAC地址
     */
    public final static String ACTION_SCANNER_FOUND = "com.ozner.mxchip.scanner.found";

    HashMap<String,String> listenDeviceList=new HashMap<>();

    final MQTTProxyImp mqttProxyImp = new MQTTProxyImp();
    MQTTProxyMxchip proxy;

//    MXChipScanImp mxChipScanImp;
    public MXChipIOManager(Context context) {
        super(context);
        proxy = new MQTTProxyMxchip(context);
        proxy.registerListener(mqttProxyImp);
//        mxChipScanImp=new MXChipScanImp(context);
    }


    public MXChipIO createMXChipDevice(String address, String type) throws ClassCastException {
        synchronized (listenDeviceList) {
            if (!listenDeviceList.containsKey(address))
                listenDeviceList.put(address, type);
        }

        if (proxy.isConnected()) {
            MXChipIO io =new MXChipIO(context(),proxy,address,type);
            doAvailable(io);
            return io;
        }else
            return null;

    }

    final static int delayedAvailableMessage=0x1000;

    @Override
    protected void doUnavailable(BaseDeviceIO io) {
        super.doUnavailable(io);
        Handler handler=new Handler(Looper.getMainLooper())
        {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what==delayedAvailableMessage)
                {
                    String address=msg.obj.toString();
                    synchronized (listenDeviceList) {
                        if (listenDeviceList.containsKey(address)) {
                            String type = listenDeviceList.get(address);
                            if (OznerDeviceManager.Instance().hashDevice(address)) {
                                MXChipIO io = createMXChipDevice(address,type);
                                if (io!=null)
                                    doAvailable(io);
                            }
                        }
                    }
                }
            }
        };

        if (!OznerDeviceManager.Instance().hashDevice(io.getAddress()))
        {
            listenDeviceList.remove(io.getAddress());
        }

        else {
            if (proxy.isConnected()) {
                Message m = new Message();
                m.what = delayedAvailableMessage;
                m.obj = io.getAddress();
                handler.sendMessageDelayed(m, 5000); //如果IO被关闭了,MQTT还是连接中的情况下,重新激活IO
            }
        }
        super.doUnavailable(io);
    }



    @Override
    public void Start(String user,String token) {
                proxy.start();
    }

    @Override
    public void Stop() {
        proxy.stop();
    }

    @Override
    protected void doChangeRunningMode() {
        super.doChangeRunningMode();
    }

    class MQTTProxyImp implements IMQTTListener {

        @Override
        public void onConnected(SMQTTProxy proxy) {
            ArrayList<String> list;
            synchronized (listenDeviceList) {
                list = new ArrayList<>(listenDeviceList.keySet());
            }

            for (String address:list) {
                MXChipIO io=new MXChipIO(context(),(MQTTProxyMxchip)proxy,address,listenDeviceList.get(address));
                doAvailable(io);
            }

        }

        @Override
        public void onDisconnected(SMQTTProxy proxy) {
            ArrayList<String> list;
            synchronized (listenDeviceList) {
                list = new ArrayList<>(listenDeviceList.keySet());
            }

            for (String address:list) {
                MXChipIO io=new MXChipIO(context(),(MQTTProxyMxchip)proxy,address,listenDeviceList.get(address));
                if (io!=null)
                doUnavailable(io);
            }
        }

        @Override
        public void onPublish(SMQTTProxy proxy, String topic, byte[] data) {

        }
    }

}
